import com.im30.jenkins.pipeline.models.ArcDiff
import com.im30.jenkins.pipeline.utils.BuildConfig

def call() {
    properties([
            parameters([
                    string(defaultValue: '', description: '', name: 'DIFF_ID', trim: false),
                    string(defaultValue: '', description: '', name: 'PHID', trim: false)
            ])
    ])

    dockerNode.javaBuildDocker {
        ArcDiff diff
        BuildConfig buildConfig
        boolean isSuccess = false
        try {
            stage('Preparation') {
                //checkout scm
                try {
                    checkout([
                            $class: 'GitSCM',
                            branches: scm.branches,
                            doGenerateSubmoduleConfigurations: false,
                            extensions: [[
                                                 $class: 'SubmoduleOption',
                                                 disableSubmodules: false,
                                                 parentCredentials: true,
                                                 recursiveSubmodules: true,
                                                 reference: '',
                                                 trackingSubmodules: false
                                         ]],
                            submoduleCfg: [],
                            userRemoteConfigs: scm.userRemoteConfigs
                    ])
                } catch (err) {
                    echo err.getMessage()
                    echo 'Try normal checkout scm'
                    checkout scm
                }

                diff = arcanistUtil.fetchArcDiff(DIFF_ID)
                arcanistUtil.applyPath(DIFF_ID, diff)
            }
            buildConfig = BuildConfig.load(this)
            stage('Test') {
                timeout(40) {
                    int status = sh(
                            encoding: 'UTF-8',
                            returnStatus: true,
                            script: 'mvn -q -U -Dmaven.test.failure.ignore clean compile test >err.log 2>&1'
                    )
                    if (status != 0) {
                        String errorLog = readFile(file: "err.log")
                        int idx = errorLog.indexOf('[ERROR] COMPILATION ERROR')
                        // 如果找不到编译错误，就展示普通错误
                        if (idx <= 0) {
                            idx = errorLog.indexOf('[ERROR]')
                        }
                        errorLog = errorLog.substring(idx)
                        throw new Exception(errorLog)
                    }
                }
            }
            stage('Report') {
                timeout (120) {
                    sh 'mvn sonar:sonar -Dsonar.analysis.mode=preview -Dsonar.host.url=http://sonar-tx.http.svc.pre.ali.im30 -Dsonar.login=27023b0400857c5d5ae67f312fcd154006a020ce | awk \'match($0, /Phab-Lint: .*/) {print substr($0, RSTART+11, RLENGTH-1)}\' | tee -a .phabricator-lint'

                    try {
                        sh 'mvn jacoco:report'
                        mavenUtil.report()
                    } catch (err) {
                        // ignore No test report files were found error
                        echo err.getMessage()
                    }

                    if (currentBuild.result == null || currentBuild.result == 'SUCCESS') {
                        if (diff != null && diff.branch == "master") {
                            sh 'echo "(WARNING) 编译通过，但不应该在 master 分支开发并提交 Diff！" >> .phabricator-comment'
                        } else {
                            sh 'echo "(NOTE) 编译通过，少年干得不错！" >> .phabricator-comment'
                        }
                        isSuccess = true
                    } else {
                        sh 'echo "(WARNING) 少年，这个提交似乎有点问题！" >> .phabricator-comment'
                        isSuccess = false
                    }
                }
            }
        } catch (err) {
            currentBuild.result = 'FAILURE'
            String errMsg = err.getMessage()
            if (errMsg != null && errMsg.length() > 10000) {
                errMsg = errMsg.substring(0, 9000) + "\n ......\n"
            }
            errMsg = "```\n${errMsg}```\n"
            sh 'echo "(IMPORTANT) 该提交无法通过通过 CI 流程！！\n\n" >> .phabricator-comment'
            sh "echo '${errMsg}' >> .phabricator-comment"
            isSuccess = false
        } finally {
            step([$class: 'PhabricatorNotifier', commentOnSuccess: true,
                  commentWithConsoleLinkOnFailure: true, coverageCheck: true,
                  coverageReportPattern: '**/target/site/jacoco/jacoco*.xml',
                  processLint: true, lintFile: '.phabricator-lint', preserveFormatting: true,
                  customComment: true, commentFile: '.phabricator-comment', commentSize: "10000"])

            try {
                notifyUtil.notifyDiff(buildConfig.getNotifyConfig(), jobUtil.getRepoName(), diff.revisionID, diff.title, isSuccess)
            } catch (err) {
                echo err.getMessage()
                echo "${buildConfig}"
                echo "${diff}"
            }

            deleteDir()
        }
    }
}